//
//  XGL_HomeViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/13.
//

import UIKit
import MXCommonModule

class XGL_HomeViewController: UIViewController,CustomNavgationBar,ScrollviewAdjustInset{
    lazy var hudView: XGL_CustomHudView = XGL_CustomHudView()
    var homeView: XGL_HomeView!
    var userHeaderView: UIImageView!
    var searchItem: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        adjustInset()
        self.createCustomBackgroundView()
        self.createXglView()
        self.creatClearNavigationBar(title: "")
        self.handleGuide()
        XGL_Notice.default.addObserver(self, selector: #selector(self.loginNoticeAction), name: XGL_Notification.login.notificationName, object: nil)
        XGL_Notice.default.addObserver(self, selector: #selector(self.publishNoticeAction), name: XGL_Notification.publish.notificationName, object: nil)
        XGL_Notice.default.addObserver(self, selector: #selector(self.addblackNoticeAction), name: XGL_Notification.addBlack.notificationName, object: nil)
        XGL_Notice.default.addObserver(self, selector: #selector(self.addblackNoticeAction), name: XGL_Notification.deleteBlack.notificationName, object: nil)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
    }

}

extension XGL_HomeViewController{
    @objc private func loginNoticeAction(){
        self.homeRequest()
    }
    @objc private func publishNoticeAction(){
        self.homeView.header.beginRefreshing()
    }
    @objc private func searchAction(){
        let vc = XGL_HomeSearchResultViewController()
        self.navigationController?.pushViewController(vc)
    }
    @objc private func addblackNoticeAction(notice: Notification){
        self.homeView.header.beginRefreshing()
    }
}


extension XGL_HomeViewController{
    private func handleGuide(){
        let data = UserDefaults.standard
        let guide = data.bool(forKey: "ShowGuide")
        if guide == false {
            data.setValue(true, forKey: "ShowGuide")
            let vc = XGL_GuideViewViewController()
            vc.completeHandler = {
                self.handleLogin()
            }
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: false, completion: nil)
        }else{
            self.handleLogin()
        }
    }
    
    private func handleLogin(){
        let infor = XGL_userDataCacheManager.shared.token
        if infor.token.isEmpty{
//            self.present(loginNaviController, animated: false, completion: nil)
            if let window = UIApplication.shared.currentWindow {
                window.rootViewController = loginNaviController
            }
        }else{
            ///start request
            self.homeRequest()
        }
    }
    
    private func homeRequest(){
        self.hudView.backgroundColor = .clear
        self.hudView.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        self.getPublishDataRequest()
        self.getuserDataDataRequest()
    }
}

extension XGL_HomeViewController: XGLHomeVideDelegate,HomeTopicDelegate{
    func refresh() {
        self.homeView.pageIndex = 1
        self.getPublishDataRequest()
    }
    
    func getMore() {
        self.getPublishDataRequest()
    }
    
    func selectPublishData(indexPath: IndexPath) {
        let model = self.homeView.videosData[indexPath.row]
        if model.data4 == "1"{
            let vc = XGL_PersonalImageDetailViewController()
            vc.detailData = model
            vc.handler = {
                self.homeView.header.beginRefreshing()
            }
            self.navigationController?.pushViewController(vc)
        }else{
            let vc = XGL_PersonalVideoDetailViewController()
            vc.detailData = model
            vc.handler = {
                self.homeView.header.beginRefreshing()
            }
            self.navigationController?.pushViewController(vc)
        }
    }
    
    func selectTopicItem(item: XGL_HomeTopicBarView.TopicItem) {
        let vc = XGL_HomeSearchResultViewController()
        vc.type = item.title
        self.navigationController?.pushViewController(vc)
    }
}



extension XGL_HomeViewController{
    private func getuserDataDataRequest(){
        PanRequestManager<XGL_RequestBaseResponse<CompleteInfor>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .PersonalInfor)) { result in
            switch result{
            case .success(let response):
                if let result = response.resultData {
                    XGL_userDataManager.share.userId = result.userId.description
                    XGL_userDataManager.share.userHeader = result.data2
                    XGL_userDataManager.share.userName = result.data1
                    self.userHeaderView.loadImageWithUrl(result.data2)
                }
                break
            default:
                break
            }
        }
    }
    
    private func getPublishDataRequest(){
        PanRequestManager<XGL_RequestBaseResponse<PageModel<PublishData>>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .GetPublishData(userId: nil, page: self.homeView.pageIndex, size: 20, data1: "2", pid: nil, data5: nil))) { result in
            switch result{
            case .success(let response):
                self.hudView.dismiss()
                if let model = response.resultData{
                    if self.homeView.header.isRefreshing{
                        self.homeView.videosData = model.data
                        self.homeView.header.endRefreshing()
                        self.homeView.footer.resetNoMoreData()
                    }else if self.homeView.footer.isRefreshing{
                        self.homeView.videosData.append(contentsOf: model.data)
                        self.homeView.footer.endRefreshing()
                    }else{
                        self.homeView.videosData = model.data
                    }
                    if model.totalPages <= model.currentPage{
                        self.homeView.footer.endRefreshingWithNoMoreData()
                    }
                    self.homeView.showDatas = self.homeView.videosData
                    self.homeView.collectionView.reloadData()
                }
                break
            default:
                self.hudView.dismiss()
                break
            }
        }
    }
}

extension XGL_HomeViewController{
    private func createXglView(){
        self.homeView = XGL_HomeView().then({ make in
            make.delegate = self
            make.topicView.delegate = self
        })
        self.view.addSubview(self.homeView)
        self.homeView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    func creatClearNavigationBar(title: String) {
        self.navigationController?.navigationBar.barStyle = .default
        setNeedsStatusBarAppearanceUpdate()
        let backColor = UIColor.clear
       
        let navView = UIView().then { make in
            make.backgroundColor = backColor
        }
        let titleView = UILabel().then { make in
            make.textColor = UIColor.white
            make.font = UIFont.pingfangSC_Semibold(fontSize: 32.0)
            make.text = title
        }
        self.searchItem = UIButton().then { make in
            make.setImage(imageWithName("icon_xgl_search_white"), for: .normal)
            make.addTarget(self, action: #selector(self.searchAction), for: .touchUpInside)
        }
        self.userHeaderView = UIImageView().then({ make in
            make.layerCornerRadius = 4.0
            make.clipsToBounds = true
        })
        navView.addSubview(titleView)
        navView.addSubview(searchItem)
        navView.addSubview(userHeaderView)
        self.view.addSubview(navView)
        
        titleView.snp.makeConstraints { make in
            make.bottom.equalTo(-16.0)
            make.left.equalTo(15.0)
        }
        userHeaderView.snp.makeConstraints { make in
            make.centerY.equalTo(titleView)
            make.left.equalTo(15.0)
            make.width.height.equalTo(36.0)
        }
        searchItem.snp.makeConstraints { make in
            make.centerY.equalTo(titleView)
            make.right.equalTo(-12.0)
            make.height.equalTo(40.0)
            make.width.equalTo(40.0)
        }
        navView.snp.makeConstraints { make in
            make.centerX.top.equalToSuperview()
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(PanNavibarH)
        }
    }
}
